package cn.tutu.blockchain.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.tutu.blockchain.common.MsgEnum;
import cn.tutu.blockchain.common.MsgObj;
import cn.tutu.blockchain.utils.HttpPostClient;
import cn.tutu.blockchain.utils.MsgUtils;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("/msg")
@Validated
public class MsgController {

	private static Logger LOGGER = LoggerFactory.getLogger(SysuserController.class);

	@RequestMapping("/sendMsg")
	public MsgObj sendMsg(@NotBlank(message = "手机号不可为空!") String phone) {

		/*
		 * String code = MsgUtils.createRandomVcode(); LOGGER.info("获取验证码,手机:{},验证码:{}",
		 * phone, code); String result = null; Map<String, String> params = new
		 * HashMap<String, String>();// 请求参数 params.put("mobile", phone);// 接收短信的手机号码
		 * params.put("tpl_id", "93183");// 短信模板ID，请参考个人中心短信模板设置 params.put("tpl_value",
		 * "#code#=" + code); params.put("key", MsgUtils.APPKEY);// 应用APPKEY(应用详细页查询)
		 * params.put("dtype", "json");// 返回数据的格式,xml或json，默认json
		 * 
		 * try { result = MsgUtils.net(MsgUtils.REQUEST_URL, params, "GET");
		 * 
		 * JSONObject object = JSONObject.fromObject(result); if
		 * (object.getInt("error_code") == 0) { MsgUtils.map.put(phone, code); //
		 * Session session = SecurityUtils.getSubject().getSession(); //
		 * session.setAttribute(phone, code); return MsgObj.buildSuccessMsg(); } else {
		 * System.out.println(object.get("error_code") + ":" + object.get("reason"));
		 * LOGGER.error("用户【{}】获取验证码失败,原因：{}", phone, object.get("reason")); return
		 * MsgObj.buildErrorMsg(MsgEnum.MSG_EXCEPTION.getCode(),
		 * MsgEnum.MSG_EXCEPTION.getMessage()); } } catch (Exception e) {
		 * LOGGER.error("用户【{}】获取验证码失败,原因：{}", phone, e); return
		 * MsgObj.buildErrorMsg(MsgEnum.MSG_EXCEPTION.getCode(),
		 * MsgEnum.MSG_EXCEPTION.getMessage()); }
		 */
		String regexp = "^1[0-9][0-9]\\d{8}$";

		boolean isMatch = Pattern.matches(regexp, phone);

		if (isMatch) {
			return juheSend(phone);
		} else {
			return fastoo(phone);
		}

	}

	private MsgObj fastoo(String phone) {
		String code = MsgUtils.createRandomVcode();
		LOGGER.info("获取验证码,手机:{},验证码:{}", phone, code);
		String msg = "【潮客云】您的验证码是" + code + "。如非本人操作，请忽略本短信";
		String parmstr = "apikey=" + MsgUtils.FASTOO_APPEKY + "&da=" + phone + "&msg=" + msg;
		MsgUtils.map.put(phone, code);
		String result = HttpPostClient.sendPost(MsgUtils.FASTOO_MSG_URL, parmstr);
		JSONObject object = JSONObject.fromObject(result);
		if (object.getString("code").equals("0")) {
			MsgUtils.map.put(phone, code);
			return MsgObj.buildSuccessMsg();
		} else {
			LOGGER.error("用户【{}】获取验证码失败,原因：{}", phone, object.get("msg"));
			return MsgObj.buildErrorMsg(MsgEnum.MSG_EXCEPTION.getCode(), MsgEnum.MSG_EXCEPTION.getMessage());
		}

	}

	private MsgObj juheSend(String phone) {
		String code = MsgUtils.createRandomVcode();
		LOGGER.info("获取验证码,手机:{},验证码:{}", phone, code);
		String result = null;
		Map<String, String> params = new HashMap<String, String>();// 请求参数
		params.put("mobile", phone);// 接收短信的手机号码
		params.put("tpl_id", "93183");// 短信模板ID，请参考个人中心短信模板设置
		params.put("tpl_value", "#code#=" + code);
		params.put("key", MsgUtils.APPKEY);// 应用APPKEY(应用详细页查询)
		params.put("dtype", "json");// 返回数据的格式,xml或json，默认json

		try {
			result = MsgUtils.net(MsgUtils.REQUEST_URL, params, "GET");

			JSONObject object = JSONObject.fromObject(result);
			if (object.getInt("error_code") == 0) {
				MsgUtils.map.put(phone, code);
				// Session session = SecurityUtils.getSubject().getSession();
				// session.setAttribute(phone, code);
				return MsgObj.buildSuccessMsg();
			} else {
				System.out.println(object.get("error_code") + ":" + object.get("reason"));
				LOGGER.error("用户【{}】获取验证码失败,原因：{}", phone, object.get("reason"));
				return MsgObj.buildErrorMsg(MsgEnum.MSG_EXCEPTION.getCode(), MsgEnum.MSG_EXCEPTION.getMessage());
			}
		} catch (Exception e) {
			LOGGER.error("用户【{}】获取验证码失败,原因：{}", phone, e);
			return MsgObj.buildErrorMsg(MsgEnum.MSG_EXCEPTION.getCode(), MsgEnum.MSG_EXCEPTION.getMessage());
		}
	}
}
